﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using DeepTime.BootStrapper.UploadedImageMetaData;
using DeepTime.BootStrapper.Utilities;
using DeepTime.Shared.Entities;
using DeepTime.BootStrapper.DataModels;
using System.Collections.ObjectModel;
using System.Windows.Data;
using DeepTime.BootStrapper.Collages;
using System.ComponentModel;

namespace DeepTime.BootStrapper.Views
{
    public partial class Home : Page
    {
        #region Class Members

        private ObservableCollection<UploadedImageCollageMetaDataDataModel> CollageImages = new ObservableCollection<UploadedImageCollageMetaDataDataModel>();
        private ObservableCollection<ImageUploader> Uploaders = new ObservableCollection<ImageUploader>();

        #endregion Class Members

        #region Constructor

        public Home()
        {
            InitializeComponent();
            LoadUploadedImages();
            icUploaders.DataContext = Uploaders;
        }

        #endregion Constructor

        #region Methods

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void LoadUploadedImages()
        {
            UploadedImageMetaDataClient proxy = ServiceHelper.CreateUploadedImageMetaDataProxy();

            proxy.GetUploadedImagesCompleted += delegate(object sndr, GetUploadedImagesCompletedEventArgs args)
            {
                if (args.Error == null)
                {
                    lbImages.DataContext = args.Result.Select<UploadedImageMetaDataEntity, UploadedImageMetaDataDataModel>(entity => new UploadedImageMetaDataDataModel(entity));
                }
            };

            proxy.GetUploadedImagesAsync();
        }

        #endregion Methods

        #region Button Event Handlers

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ImageUploader uploader = new ImageUploader();

            //
            // Subscribe to completed event
            //
            uploader.CleaUploadImageCompletedEventHandlers();
            uploader.UploadImageCompleted += (object sndr, UploadImageCompletedEventArgs args) =>
            {
                if (args.Successful)
                {
                    Uploaders.Remove(uploader);
                    LoadUploadedImages();
                }
            };

            //
            // Prompt for file
            //
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Multiselect = false;
            dlg.Filter = "Image Files (*.bmp, *.jpg)|*.bmp;*.jpg";

            if (dlg.ShowDialog().GetValueOrDefault())
            {
                Uploaders.Add(uploader);
                uploader.Upload(dlg.File, new Uri(Application.Current.Host.Source, "../Image.aspx").ToString());
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            CollageImages.Clear();
            cCollage.Children.Clear();
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            UploadedImageMetaDataDataModel data = ((Button)sender).DataContext as UploadedImageMetaDataDataModel;
            NavigationService.Navigate(new Uri("/DeepZoomImages", UriKind.Relative));
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            Button b = sender as Button;

            if (b == null) return;

            UploadedImageMetaDataDataModel tmpData = b.DataContext as UploadedImageMetaDataDataModel;

            if (tmpData == null) return;

            UploadedImageCollageMetaDataDataModel data = new UploadedImageCollageMetaDataDataModel(tmpData);

            CollageImages.Add(data);

            Image i = new Image();
            i.MouseMove += new MouseEventHandler(i_MouseMove);
            i.MouseLeave += new MouseEventHandler(i_MouseLeave);
            i.MouseLeftButtonDown += new MouseButtonEventHandler(i_MouseLeftButtonDown);
            i.MouseLeftButtonUp += new MouseButtonEventHandler(i_MouseLeftButtonUp);

            i.MaxWidth = 200;
            i.MaxHeight = 200;
            i.DataContext = data;

            Binding blobBinding = new Binding("BlobUri") 
            { 
                Mode = BindingMode.OneWay,
                Converter = new BlobUriToImageURLConverter(),
            };

            Binding leftBinding = new Binding("X")
            {
                Mode = BindingMode.TwoWay,
            };

            Binding topBinding = new Binding("Y")
            {
                Mode = BindingMode.TwoWay,
            };

            BindingOperations.SetBinding(i, ImageExtensionBehaviours.RelativeSourceProperty, blobBinding);
            BindingOperations.SetBinding(i, Canvas.LeftProperty, leftBinding);
            BindingOperations.SetBinding(i, Canvas.TopProperty, topBinding);

            cCollage.Children.Add(i);
        }

        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            CollagesClient proxy = ServiceHelper.CreateCollagesProxy();

            proxy.CreateCompleted += delegate(object sndr, AsyncCompletedEventArgs args)
            {
                CollageImages.Clear();
                cCollage.Children.Clear();
            };

            ObservableCollection<UploadedImageCollageMetaDataEntity> collageEntities = new ObservableCollection<UploadedImageCollageMetaDataEntity>(CollageImages.Select<UploadedImageCollageMetaDataDataModel, UploadedImageCollageMetaDataEntity>(dataModel => dataModel.GetEntity()));
            proxy.CreateAsync(collageEntities);
        }

        #endregion Button Event Handlers

        #region Image Event Handlers

        void i_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Image i = sender as Image;

            if (i == null) return;

            MouseExtensionBehaviours.SetIsMouseButtomDown(i, false);
            MouseExtensionBehaviours.SetDownPosition(i, new Point());
        }

        void i_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Image i = sender as Image;

            if (i == null) return;

            MouseExtensionBehaviours.SetIsMouseButtomDown(i, true);
            MouseExtensionBehaviours.SetDownPosition(i, e.GetPosition(i));
        }

        void i_MouseLeave(object sender, MouseEventArgs e)
        {
            Image i = sender as Image;

            if (i == null) return;

            MouseExtensionBehaviours.SetIsMouseButtomDown(i, false);
            MouseExtensionBehaviours.SetDownPosition(i, new Point());
        }

        void i_MouseMove(object sender, MouseEventArgs e)
        {
            Image i = sender as Image;

            if (i == null) return;

            if (MouseExtensionBehaviours.GetIsMouseButtomDown(i))
            {
                Point mousePositionOnImage = MouseExtensionBehaviours.GetDownPosition(i);
                Point mousePositionOnCanvas = e.GetPosition(cCollage);

                double newImageLeft = mousePositionOnCanvas.X - mousePositionOnImage.X;
                double newImageTop = mousePositionOnCanvas.Y - mousePositionOnImage.Y;

                UploadedImageCollageMetaDataDataModel data = i.DataContext as UploadedImageCollageMetaDataDataModel;

                if (data == null) return;

                data.X = newImageLeft;
                data.Y = newImageTop;
            }
        }

        #endregion Image Event Handlers
    }
}
